package cn.jiangzeyin.controller.classifiers.corpus;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.jiangzeyin.common.DefaultSystemLog;
import cn.jiangzeyin.common.JsonMessage;
import cn.jiangzeyin.controller.classifiers.BaseClassification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

/**
 * Created by jiangzeyin on 2017/12/9.
 */
@RestController
@RequestMapping("classifiers/corpus")
public class ClassificationCorpus extends BaseClassification {

    /**
     * 获取所有分类名称
     *
     * @return json 格式
     */
    @RequestMapping(value = "category.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String category() {
        String tip = doCorpusFolder();
        if (tip != null) {
            return tip;
        }
        File file = new File(corpusFolder);
        String[] category = file.list();
        return JsonMessage.getString(200, "success", category);
    }


    /**
     * 添加分类词库中的内容
     *
     * @param category   分类名称
     * @param documentId 文件名（id）
     * @param document   文件内容
     * @return json
     */
    @RequestMapping(value = "add.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String add(String category, String documentId, String document) {
        String tip = doCorpusFolder();
        if (tip != null) {
            return tip;
        }
        if (StrUtil.isEmpty(category)) {
            return JsonMessage.getString(400, "category is null");
        }
        if (StrUtil.isEmpty(documentId)) {
            return JsonMessage.getString(400, "documentId is null");
        }
        if (StrUtil.isEmpty(document)) {
            return JsonMessage.getString(400, "document is null");
        }
        category = replacePath(category);
        documentId = replacePath(documentId);
        String path = FileUtil.normalize(corpusFolder + "/" + category + "/" + documentId + ".txt");
        try {
            FileUtil.writeString(document, path, CharsetUtil.CHARSET_UTF_8);
            //.writerFile(path, document);
        } catch (IORuntimeException e) {
            DefaultSystemLog.ERROR().error("写document 文件异常", e);
            return JsonMessage.getString(500, "writer document error", e.getMessage());
        }
        return JsonMessage.getString(200, "success");
    }
}
